package armserver.log4j;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.management.Notification;
import javax.management.NotificationBroadcasterSupport;

import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggerRepository;

public class Log4jConfig  extends NotificationBroadcasterSupport implements Log4jConfigMBean{

	private static final Logger log = Logger.getLogger(Log4jConfig.class);
	
	public String[] getLog4jList() {
		LoggerRepository lr = LogManager.getLoggerRepository();
		Enumeration enumList = lr.getCurrentLoggers();
		Logger logger=null;
		List logList = new ArrayList();
		while(enumList.hasMoreElements())
		{
			logger = (Logger) enumList.nextElement();
			logList.add(logger.getName());
		}
		return (String[]) logList.toArray(new String[]{});
	}

	public void setLog4jLevel(String target, String level) {
		Logger logger = LogManager.exists(target);
		Level oldLevel=null;
		if(logger!=null)
		{
			if(level==null)
			{
				return;
			}
			if(level.equalsIgnoreCase("INFO"))
			{
				logger.setLevel(Level.INFO);
			}
			if(level.equalsIgnoreCase("DEBUG"))
			{
				logger.setLevel(Level.DEBUG);
			}
			if(level.equalsIgnoreCase("ERROR"))
			{
				logger.setLevel(Level.ERROR);
			}
			if(level.equalsIgnoreCase("FATAL"))
			{
				logger.setLevel(Level.FATAL);
			}
			if(level.equalsIgnoreCase("WARN"))
			{
				logger.setLevel(Level.WARN);
			}
			if(level.equalsIgnoreCase("TRACE"))
			{
				logger.setLevel(Level.TRACE);
			}
			if(level.equalsIgnoreCase("OFF"))
			{
				logger.setLevel(Level.OFF);
			}
			oldLevel = logger.getLevel();
		}
		
		this.sendNotification(new Notification("LOGCHANGE", this, 0, System.currentTimeMillis(), "log from "+oldLevel.toString()+" to "+level));
		
	}

	public String getLog4jLevel(String target) {
		
		Logger logger = LogManager.exists(target);
		if(logger!=null)
		{
			return logger.getLevel().toString();
		}
		return null;
	}

}
